var seriesPage = new Class({ 
	Extends: modalController,
	// options: {
	// 	customClass: '',
	// 	customTitle: '',
	// 	customURI: ''
	// },
	seriaID: 0,
	seriaData: {},
	seasonsCont: {},
	imageElements: [],
	blankImg: '/assets/blank.gif',
	hash: '',
	jumpOnReady: '',
	spinner: $empty(),
	initModal: function(name, season, episode){
		this.name = name;
		this.enableInstantJump(season, episode);
	},
	loadData: function(){
		var self = this;
		new Request.JSON({
			url: api + 'seriesbyname.json|' + this.name,
			onRequest: function(){
				self.addSpinner('start');
			},
			onComplete: function(){
				self.addSpinner('stop');
			},
			onSuccess: function(json){
				if(typeOf(json) == 'object')
					self.loadPage(json)
			}
		}).send();
	},
	addSpinner: function(opt){
		var spinglower = function(){
			this.spinner.tween('opacity', [.5,.8]);
			this.spinner.tween('opacity', [.8,.5]);
		};
		switch(opt)
		{
			default:
			case "start":
				this.spinner = $("wrapper").addSpinner();
				this.spinner.set('tween', {link: 'chain'});
				spinglower.run(null,this);
				this.spinner.p = spinglower.periodical(5000, this);
			break;
			
			case "stop":
				$("wrapper").removeSpinner(); 
				$clear(this.spinner.p);
				this.spinner = $empty();
			break;
		}
	},
	loadContent: function(json){
		var self = this;
		this.seriaData = json;
		if(typeof this.seriaData != 'object' || !'serie' in this.seriaData)
			return this.dispose(true);
		this.setOptions({customURI: 's/' + this.name, customTitle: this.seriaData.serie.seriesname});

		var topBtnCont = new Element('div.topBtnCont').inject(this.page);
		var topCentBtnCont = new Element('div.viewStatusSwitches').inject(this.page);
		
		var totopbtn = new Element('a.toTopBtn', {href: '#top', html: 'Tetejére'}).inject(topBtnCont);
		var closebtn = new Element('a.closebtn[title=Bezárás (X)][accesskey=X]', {html: 'Bez&aacute;r&aacute;s'})
		.inject(topBtnCont)
		.addEvent('click', function(){
			self.dispose();
		});
		k.addNew(closebtn);
		
		var wrap = new Element('div.wrap').inject(this.page);
		var h2title = new Element('h2', {text: json.serie.seriesname}).inject(wrap);
		
		if(userstatus.isLoggedin){
			new Element('a', {html: 'Sorozat k&ouml;vet&eacute;se', 'rel' : 'Sorozat követése', 'class' : 'followIcon ir' + ((userstatus.userData.user_settings.user_series.contains(json.serie.id)) ? ' checked' : '')})
			.inject(h2title)
			.addEvent('click', function(){
				new Request({
		        async: false,
		        url:  api + 'userseries.json|add|' + json.serie.id
		    }).send();
				userstatus.updateStatus();
				this.toggleClass('checked');
			});
		}
		
		if('bannermd5' in json.serie)
		new Element('div.img', {styles: {
			'backgroundImage': 'url(/image/series/' + json.serie.bannermd5 + '/640)'
		}}).inject(wrap);
		var shortDesc;
		if(json.serie.overview.length > 255)
			shortDesc = json.serie.overview.substr(0, 255) + '...&nbsp;';	
			
		var descCont = new Element('div.description', {html : json.serie.overview}).inject(wrap);
		
		if(shortDesc)
		{
			descCont.addClass('shortT');
			descCont.set('html', shortDesc);
			new Element('a', {'html' : 'T&ouml;bb...'})
			.inject(descCont)
			.addEvent('click', function(){
				if(descCont.hasClass('shortT'))
				{
					descCont.removeClass('shortT');
					descCont.set('html', json.serie.overview);
					this.inject(descCont);
				}
				else
				{
					descCont.addClass('shortT');
					descCont.set('html', shortDesc);
					this.inject(descCont);
				}
			});
		}

		
		var rdata = new Element('div.rawdata').inject(h2title, 'after');
		//Először adásban
		this.dList('El&#x151;sz&ouml;r ad&aacute;sban', ((json.serie.firstaired == '0000-00-00') ? 'ismeretlen' : new Date().parse(json.serie.firstaired).format('%Y.%m.%d.'))).inject(rdata);
		//Adásban nap + időpont

		var onair = ((!json.serie.airs_dayofweek) ? 'ismeretlen nap' : json.serie.airs_dayofweek) + ' ';
		onair += ((!json.serie.airs_time) ? '' : json.serie.airs_time);
		
		this.dList('Ad&aacute;sban', onair).inject(rdata);
		
		this.dList('J&aacute;t&eacute;kid&#x151;', ((!json.serie.runtime) ? 'ismeretlen' : json.serie.runtime + ' perc')).inject(rdata);
		this.dList('Csatorna', ((!json.serie.network) ? 'ismeretlen' : json.serie.network)).inject(rdata);
		this.dList('M&#x171;faj', ((!json.serie.genre) ? 'ismeretlen' : json.serie.genre.replace(/^\||\|$/g, '').split('|').join(', '))).inject(rdata);	
	

		//order seasons
		var seasons = new Object();
		Array.each(json.episodes, function(elem){
			if(!seasons[elem.seasonnumber])
				seasons[elem.seasonnumber] = [];
			seasons[elem.seasonnumber].push(elem);
		});
		
		var pagination = new Element('div.pagination').inject(wrap);
		
		self.seasonsCont = new Element('div.seasons').inject(wrap);
		
		//viewStatusSwitches	
		var detailV = new Element('input[type=radio][name=viewSwitch]').inject(new Element('label.ir.detailView').inject(topCentBtnCont));	
		var listV = new Element('input[type=radio][name=viewSwitch]').inject(new Element('label.ir.listView').inject(topCentBtnCont));
			
		Object.each(seasons, function(elem, key){
			var seasnum = new Element('h2.close#s'+key, {html: key + '. &eacute;vad'}).inject(self.seasonsCont);
			new Element('span', {html: '&#x2023;'}).inject(seasnum, 'top');
			new Element('a', {html: '&equiv;'})
			.inject(seasnum)
			.addEvent('click', function(e){
				e.preventDefault();
				self.seasonsCont.getChildren('h2').addClass('close');
			});
			
			seasnum.addEvent('click', function(e){
				e.preventDefault();
				if(e.target.get('tag') != 'a')
				this.toggleClass('close');
				self.page.fireEvent('scroll');
			});
			
			new Element('a', {href : '#s' + key, text : key}).inject(pagination);
			var leftScroll = this.getScroll().x;
			//scrolling Season Number
			self.page.addEvent('scroll', function(){

				if(this.getScroll().y > seasnum.getPosition(this).y && !seasnum.hasClass('hasclone') && !seasnum.hasClass('close'))
				{
					seasnum.addClass('hasclone');
					seasnum.clone().inject(seasnum, 'after').addClass('out').setStyle('left', seasnum.getPosition(this).x - this.getScroll().x);
				}
				else if(this.getScroll().y < seasnum.getPosition(this).y && seasnum.hasClass('hasclone'))
				{
					seasnum.removeClass('hasclone');
					seasnum.getNext('h2.out').dispose();
				}		
				else if(this.getScroll().x != leftScroll && seasnum.hasClass('hasclone'))
				{
					seasnum.getNext('h2.out').setStyle('left', seasnum.getPosition(this).x - this.getScroll().x);
				}
					
			});
			
			var cul = new Element('ul').inject(self.seasonsCont);
			elem.each(function(row){
				var cli = new Element('li', {id : 'ep' + key + 'x' + row.episodenumber}).inject(cul);
				cli.addEvent('click', function(e){
					if(e.target.get('tag').test(/(a|img)/))
						return true;
					e.preventDefault();
					this.toggleClass('list');
				});
				new Element('span.num', {text : 'x' + row.episodenumber}).inject(cli);
				var epttl = new Element('div.title', {html: row.episodename}).inject(cli);
				new Element('a.ir', {href: '/e/' + escape(json.serie.seriesname) + '/' + key + 'x' + row.episodenumber}).inject(epttl);

				new Element('div.onair', {html: ((row.firstaired && row.firstaired != '0000-00-00') ? new Date().parse(row.firstaired).format('%Y.%m.%d.') : 'TBA')}).inject(cli);
				new Element('div.overview', {html: row.overview}).inject(cli);
				
				if(row.filenamemd5)
				{
					var epima = new Element('a.img', {href: '/image/episode/' + row.filenamemd5, styles: {width:150,height:84}}).inject(cli, 'top');
					var epimathumb = '/image/episode/' + row.filenamemd5 + '/150x84';
					self.imageElements.include(new Element('img', {src : self.blankImg, alt : row.episodename, styles: {width:150,height:84}}).inject(epima).store('oSRC', epimathumb));
					epima.addEvent('click', function(e){
						e.preventDefault();
						if(!this.hasClass('big'))
						{
							this.addClass('big');
							this.getElement('img').set('src', this.get('href'));						
						}
						else {
							this.removeClass('big');
							this.getElement('img').set('src', epimathumb);
						}		
						this.getElement('img').fireEvent('imgchange');
					});
					
					epima.getElement('img').addEvent('imgchange', function(){
						var self = this;
						var img = new Image();
						img.src = self.get('src');
						img.onload = function(){$$(epima, self).morph({width: img.width, height: img.height});}; 				
					});
				}
				
			});
		});
		self.viewSwitches(detailV, listV);		
		
		this.box.inject(this.container, 'bottom');
		
		
		var scrollSpage = new Fx.Scroll(this.page);
		totopbtn.addEvent('click', function(e){
			e.preventDefault();
			scrollSpage.toTop();
		});
		pagination.getElements('a').addEvent('click', function(e){
			e.preventDefault();
			$(this.get('href').substr(1)).removeClass('close');
					
			scrollSpage.start(self.box.getScroll().x, $(this.get('href').substr(1)).getPosition().y);
		});
		
		if(this.jumpOnReady && $(this.jumpOnReady))
		{
			$(this.jumpOnReady)
			.removeClass('list')
			.getParent('ul')
			.getPrevious('h2')
			.removeClass('close');	
			
			scrollSpage.set(self.box.getScroll().x, $(this.jumpOnReady).getPosition(self.box).y-35);		
			var jumTween = new Fx.Tween($(this.jumpOnReady), {link: 'chain'});
			(function(){
				var curBg = $(this.jumpOnReady).getStyle('backgroundColor');
				curBg = (curBg == 'transparent') ? (this.lightSwitchElement.hasClass('on')) ? '#ddd' : '#141414' : curBg;
				
				jumTween.start('backgroundColor', curBg, '#3d8bff');
				jumTween.start('backgroundColor', curBg)
				.chain(
					function(){
						$(this.jumpOnReady).setStyle('backgroundColor');
					}.bind(this)
				);
			}).delay(1000, this);
		}
		
		var imgLoading = function(){
			this.imageElements = this.imageElements.filter(function(el){
				if((this.page.getScroll().y + 200 + this.page.getSize().y) >= el.getPosition(this.page).y && el.isVisible()) {
					if(el.retrieve('oSRC')) { el.set('src',el.retrieve('oSRC')).setStyles({width: 150, height: 84}); }
					
					return false;
				}
				return true;
			}, this);
		}.bind(this);
		
		this.page.addEvent('scroll', function(){
			if(this.getScroll().y > 200 && !totopbtn.isDisplayed())
				totopbtn.addClass('show');
			else if(this.getScroll().y <= 200 && totopbtn.isDisplayed())
				totopbtn.removeClass('show');											
		});
		
		this.page.addEvent('scroll', imgLoading.bind(self));
		this.box.fade('in');
		(function(){self.page.fireEvent('scroll');}).delay(200);
	},
	dList: function(dttext, ddtext){
		var dl = new Element('dl');
		var dt = new Element('dt', {'html' : dttext}).inject(dl);
		var dd = new Element('dd', {'html' : ddtext}).inject(dl);
		return dl;
	},
	viewSwitches: function(detailView, listView)
	{
		var self = this;
		var checkSwitch = function(elem){
			var elbl = elem.getParent('label');
			
			if(elem.get('checked'))
				elbl.addClass('checked');
			else
				elbl.removeClass('checked')
			
		};
		var setSeasonsStatus = function(){
			if(listView.get('checked'))
				self.seasonsCont.getElements('li').addClass('list');
			else
				self.seasonsCont.getElements('li').removeClass('list');
			Cookie.write('sc_searialistview', (listView.get('checked') ? 1 : 0), {duration: 14, path: '/'});
				
		};
		
		if((Cookie.read('sc_searialistview') || 1).toInt())
			listView.set('checked', true);
		else
			detailView.set('checked', true);
		
		$$(detailView, listView).each(checkSwitch);
		setSeasonsStatus();
		
		$$(detailView, listView).addEvent('click', function(){
			$$(detailView, listView).each(checkSwitch);
			setSeasonsStatus();
		});
		
	},
	enableInstantJump: function(season, episode){
		this.jumpOnReady = ((!season || !episode) ? ((season) ? 's' + season : '') :  'ep' + season + 'x' + episode);
	}
});